<?php
/**
 * Created by PhpStorm.
 * User: Edward
 * Date: 2019/6/5
 * Time: 11:13
 */

namespace app\admin\controller\shop;


use app\admin\BaseController;
use app\admin\model\Money;
use app\admin\model\MoneyRecord;
use app\admin\model\UserDemand;
use app\admin\model\Warehouse;
use app\admin\model\WarehouseListDetail;
use app\api\model\ProductOrder;
use app\api\model\ProductOrderDetail;
use app\api\model\ProductOrderRelation;
use app\api\model\ProductOrderReturn;
use app\api\model\ProductReview;
use app\common\controller\DateCommon;
use app\common\model\ProductOrderSpell;
use app\lib\exception\FailedException;
use app\lib\exception\NotFoundException;
use app\Validate\ActionMustPositiveValidate;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;
use app\Validate\TypeValidate;
use think\Db;
use think\Request;

class Order extends BaseController {
    /**
     * 查询订单
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function shopOrder(Request $request){
        (new TypeValidate())->goCheck();
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $where= [];
        $where = addWhere($post,['return_status'=>'','pay_style'=>'','status'=>''],$where,1);
        $where = addWhere($post,['order_number'=>''],$where,2);
        if(isset($post['type'])){
            $where_shop = [
                ['type','eq',$post['type']],
                ['status','eq',2],//
            ];

            if(isset($post["uid"])){
                $where_shop[] = ["id","eq",$post["uid"]];
            }

            $uidList = (new \app\admin\model\Shop())->where($where_shop)->column("id");
            if($post['type'] == 3){
                //-1为万享集订单
                array_push($uidList,-1);
            }
            $where[] = ['uid','in',$uidList];
        }

        //申请时间
        if(isset($post['min_time'])&&isset($post['max_time'])&&$post['min_time']!=""&&$post['max_time']!=""){
            $post['min_time'] = strtotime($post['min_time']);
            $post['max_time'] = strtotime($post['max_time']);
            $where[] = ['create_time','between',[$post['min_time'],$post['max_time']]];
        }elseif (isset($post['min_time'])&&$post['min_time']!=""){
            $post['min_time'] = strtotime($post['min_time']);
            $where[] = ['create_time','egt',$post['min_time']];
        }elseif (isset($post['max_time'])&&$post['max_time']!=""){
            $post['max_time'] = strtotime($post['max_time']);
            $where[] = ['create_time','elt',$post['max_time']];
        }
        $where['page'] = $post['page'];
        $with = ['orderDetail', 'orderDetail'=>['tradeHall','product']];//多关联不同源要数组嵌套
        $dataList = (new ProductOrder())->wechatListTotalWith($with,$where,"*","id desc",$post['page_number']);
        foreach ($dataList["data"] as $k=>$v){
            if($v["pay_style"] == 3){ $dataList["data"][$k]["tags"] = ["货到付款"];}
            else{ $dataList["data"][$k]["tags"] = ["正常付款"];}
        }
        return writeJson(200,$dataList);
    }

    /**
     * 订单详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function shopOrderDetail(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $detail = (new ProductOrder())->findOneWith("orderDetail",[['id','eq',$post['id']]]);

        if($detail["order_type"] == 3){
            //查询本订单所有参团人
            $detail["spell_user"] = (new ProductOrderSpell())->getOrderSpell($detail["id"]);
        }
        //获取当前订单团起
        return writeJson(200,['detail'=>$detail]);
    }

    /**
     * 订单评价
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function shopOrderReview(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $admin =$this->admin;
        $where= [];
        $where = addWhere($post,['phone'=>''],$where,2,'b.');//用户名称
        $where = addWhere($post,['name'=>''],$where,2,'c.');//商家名称
        if($admin['account_type']==2){ //如果是商家账号
            $where[] = ['a.uid','eq',$admin['uid']];
        }

        //申请时间
        $DateCommon = new DateCommon();
        if(isset($post['min_time'])&&isset($post['max_time'])&&$post['min_time']!=""&&$post['max_time']!=""){
            $post['min_time'] = $DateCommon->OutUnixByTime($post['min_time']);
            $post['max_time'] = $DateCommon->OutUnixByTime($post['max_time']);
            $where[] = ['a.create_time','between',[$post['min_time'],$post['max_time']]];
        }elseif (isset($post['min_time'])&&$post['min_time']!=""){
            $post['min_time'] = $DateCommon->OutUnixByTime($post['min_time']);
            $where[] = ['a.create_time','egt',$post['min_time']];
        }elseif (isset($post['max_time'])&&$post['max_time']!=""){
            $post['max_time'] = $DateCommon->OutUnixByTime($post['max_time']);
            $where[] = ['a.create_time','elt',$post['max_time']];
        }

        $field = "a.*,b.phone,c.name,d.order_number";
        $dataList = (new ProductReview())
            ->alias("a")
            ->join("om_user b","a.user_id = b.id","left")
            ->join("om_shop c","a.uid = c.id","left")
            ->join("om_product_order d","a.order_id = d.id","left")
            ->field($field)
            ->where($where)
            ->order("a.id desc")
            ->paginate($post['page_number'],false ,['page' => $post['page']])->each(function ($item){
                return $item;
            });
        $dataList = $dataList->toArray();
        $returnData = [
          'data' =>$dataList['data'],
          'count' =>$dataList['total']
        ];
        return writeJson(200,$returnData);
    }

    /**
     * 生成出库单
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function makeOrder(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $where_order = [['id','eq',$post['id']],['status','eq',1]];
        $order = (new ProductOrder())->findOne($where_order);
        if(!$order){ throw new NotFoundException(['msg'=>'订单不存在']); }

        $where = [['order_id','eq',$post['id']]];
        $detail = (new ProductOrderDetail())->selectList($where);
        if(!$detail){ throw new NotFoundException(['msg'=>'订单详情不存在']); }
        $detail = $detail->toArray();
        foreach ($detail as $key=>$value){
            $detail[$key]['sku'] = $value['product_sku'];
            $detail[$key]['actual_stock'] = $value['number'];
        }
        $uid = $order['uid'];
        $where_shop = [
            ['id','eq',$uid],
            ['status','eq',2],
            ['use_status','eq',1]
        ];
        $shop = (new \app\admin\model\Shop())->findOne($where_shop);
        if(!$shop){
            //如果查询不到商家，则为交易大厅的商品
            $shop["type"] = 3;
        }
        $warehouse_id = 2;//默认中转仓库
        if($shop["type"] == 1 || $shop["type"] == 2){
            //品牌商与线上商家订单查询自己仓库的库存
            $warehouse_id = (new Warehouse())->findOne([['uid','eq',$uid]],"id");
        }

        Db::startTrans();
        //生成出库单
        $new = [
            'type'=>3,
            'uid'=>$uid,
            'warehouse_id'=>$warehouse_id,
            'total_stock'=>0,
            'order_number'=>(new \app\admin\model\WarehouseList())->createOrderNumber("WL"),
            'edit_status' =>2,
            'status'      =>2,
            'remark' =>"发货单"
        ];
        foreach($detail as $key=>$value){
            $new['total_stock']+=$value['number'];
        }
        $list_id = (new \app\admin\model\WarehouseList())->dataUpdate($new);
        if(!$list_id){
            Db::rollback();
            throw (new FailedException(['msg'=>'添加总订单失败']));
        }
        $newList = [];
        foreach ($detail as $key=>$value){
            $newList[] =[
                'uid'    =>$value["uid"],
                'list_id'=>$list_id,
                'product_id'=>$value['product_id'],
                'sku'=>$value['sku'],
                'plan_stock'=>$value['actual_stock'],//计划入库
                'actual_stock'=>$value['actual_stock'],//实际入库
                'product_time'=>isset($value['product_time'])?strtotime($value['product_time']):time(),//生产时间
                'warning_time'=>isset($value['warning_time'])?strtotime($value['warning_time']):time(),//预警时间
                'warning_stock'=>isset($value['warning_stock'])?$value['warning_stock']:0,//预警库存
                'remark'=>isset($value['remark'])?$value['remark']:"",//批次的备注
                'batch_number'=>isset($value['batch_number'])?$value['batch_number']:"",//批次号
                'create_time'  =>time(),
                'update_time'  =>time(),
            ];
            if($order["order_type"] != 3){  //除了拼团外 其他商品需要去库存 拼团在支付回调后去库存
                //商品去库存
                $res = orderChangeStock($value['product_id'],$value['number'],$warehouse_id);
                if(!$res){
                    Db::rollback();
                    throw (new FailedException(['msg'=>'生成订单失败']));
                }
            }
        }
        $res = (new WarehouseListDetail())->saveAll($newList);
        if(!$res){
            Db::rollback();
            throw (new FailedException(['msg'=>'生成订单失败']));
        }

        $new = [
            'id'=>$post['id'],
            'status'=>2, 'send_time'=>time(),
            'express_name'=>isset($post['express_name'])?$post['express_name']:"",
            'express_number'=>isset($post['express_number'])?$post['express_number']:""
        ];
        $res = (new ProductOrder())->dataUpdate($new);
        if(!$res){
            Db::rollback();
            throw new FailedException(['msg'=>'修改订单失败']);
        }
        Db::commit();
        return writeJson(200,[],'生成发货单成功');
    }

    /**
     * 更改订单状态
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function editOrderStatus(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        if(!isset($post['status'])){ throw new FailedException(['msg'=>'参数有误请查正']); }
        $where["id"] = $post['id'];
        $res = (new ProductOrder())->fieldUpdate("status",$post['status'],"",$where);
        if(!$res){
            throw new FailedException(['msg'=>'修改订单失败']);
        }

        //处理返佣 当状态为确认收货或已完成时，进行返佣，并记录完成时间。
        if($post['status'] == 1 || $post['status'] == 2){
            (new \app\api\model\Money())->insertInviteRecord($post['id']);
        }
        //保存确认时间
        if($post['status'] == 4){
            (new ProductOrder())->where($where)->update(['sure_time'=>time()]);//4是已完成
        }
        return writeJson(200,[],'操作成功');
    }

    /**
     * 商家订单列表
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function onLineOrder(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $admin = $this->admin;
        if($admin['account_type']!=2){ //如果是商家账号
            throw new FailedException(['msg'=>'不属于商家账号']);
        }
        $where= [];
        $where[] = ['uid','eq',$admin['uid']];
        $where = addWhere($post,['return_status'=>'','pay_style'=>'','status'=>''],$where,1);
        $where = addWhere($post,['order_number'=>''],$where,2);
        //申请时间
        if(isset($post['min_time'])&&isset($post['max_time'])&&$post['min_time']!=""&&$post['max_time']!=""){
            $post['min_time'] = strtotime($post['min_time']);
            $post['max_time'] = strtotime($post['max_time']);
            $where[] = ['create_time','between',[$post['min_time'],$post['max_time']]];
        }elseif (isset($post['min_time'])&&$post['min_time']!=""){
            $post['min_time'] = strtotime($post['min_time']);
            $where[] = ['create_time','egt',$post['min_time']];
        }elseif (isset($post['max_time'])&&$post['max_time']!=""){
            $post['max_time'] = strtotime($post['max_time']);
            $where[] = ['create_time','elt',$post['max_time']];
        }
        $where['page'] = $post['page'];
        $dataList = (new ProductOrder())->wechatListTotalWith("orderDetail,user",$where,"*","id desc",$post['page_number']);
        return writeJson(200,$dataList);
    }

    /**
     * 商家维权订单列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function onLineReturnOrder(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $admin = $this->admin;
        $where= [];
        if($admin['account_type']==2){ //如果是商家账号
            $where[] = ['uid','eq',$admin['uid']];
        }

        $where = addWhere($post,['status'=>''],$where,1); //维权状态退款处理进度 -1 是已驳回0是 待处理 1是已处理 2是待收货 3是已完成

        //申请时间
        if(isset($post['min_time'])&&isset($post['max_time'])&&$post['min_time']!=""&&$post['max_time']!=""){
            $post['min_time'] = strtotime($post['min_time']);
            $post['max_time'] = strtotime($post['max_time']);
            $where[] = ['create_time','between',[$post['min_time'],$post['max_time']]];
        }elseif (isset($post['min_time'])&&$post['min_time']!=""){
            $post['min_time'] = strtotime($post['min_time']);
            $where[] = ['create_time','egt',$post['min_time']];
        }elseif (isset($post['max_time'])&&$post['max_time']!=""){
            $post['max_time'] = strtotime($post['max_time']);
            $where[] = ['create_time','elt',$post['max_time']];
        }
        $where['page'] = $post['page'];

        $dataList = (new ProductOrderReturn())->wechatListTotalWith("orderDetail,productOrder",$where,"*","id desc",$post['page_number']);
        foreach ($dataList['data'] as &$value){
            foreach ($value['order_detail'] as &$val){
                $val['product_cover_img'] = imgUrlToAbsolute($val['product_cover_img']);
            }
        }

//         //查询商家下的所有订单
//        $dataList = (new ProductOrderReturn())
//            ->field("*")
//            ->join("om_product_order_detail_return","om_product_order_detail_return.order_return_id = om_product_order_return.id")
//            ->join("om_product_order","om_product_order.id = om_product_order_return.relation_id")
//            ->where($where)
//            ->paginate($post['page_number'],false ,['page' => $post['page']])->each(function ($item){
//                return $item;
//            });
//
//        foreach ($dataList as &$value){
//            foreach ($value['order_detail'] as &$val){
//                $val['product_cover_img'] = imgUrlToAbsolute($val['product_cover_img']);
//            }
//        }
        return writeJson(200,$dataList);
    }

    /**
     * 退款维权订单详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function ReturnOrderDetail(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $returnDetail = (new ProductOrderReturn())->findOneWith('orderDetail',[['id','eq',$post['id']]]);
        foreach ($returnDetail['order_detail'] as &$value){
            $value['product_cover_img'] = imgUrlToAbsolute($value['product_cover_img']);
        }
        $orderDetail = (new ProductOrder())->findOneWith("orderDetail",[['id','eq',$returnDetail['relation_id']]]);
        foreach ($orderDetail['order_detail'] as &$value){
            $value['product_cover_img'] = imgUrlToAbsolute($value['product_cover_img']);
        }
        return writeJson(200,['orderDetail'=>$orderDetail,'returnDetail'=>$returnDetail]);
    }

    /**
     * 退款审核列表
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
     public function checkReturnOrder(Request $request){
         (new IdMustPositive())->goCheck();
         (new ActionMustPositiveValidate())->goCheck();
         $post = $request->post();
         $orderDetail = (new ProductOrderReturn())->findOne([['id','eq',$post['id']]]);
         if(!$orderDetail){
             throw new NotFoundException(['msg'=>'订单不存在']);
         }
         //审核操作
         if($post['action_type']=='check'){
             if($orderDetail['status']!=0){
                 throw new FailedException(['msg'=>'订单已审核']);
             }
             $new = [
               'id' =>$post['id'],
               'status'=>$post['check_status'] //1是通过 -1是驳回
             ];
             if(!in_array($post['check_status'],[-1,1])){
                 throw new FailedException(['msg'=>'审核状态不正确']);
             }
             $res = (new ProductOrderReturn())->dataUpdate($new);
             if(!$res){
                 throw new FailedException(['msg'=>'审核失败']);
             }
             return writeJson(200);
         }
         //确认完成操作
         if($post['action_type']=="cancel"){
             $product_order = (new ProductOrder())->findOne([['id','eq',$orderDetail['relation_id']]]);
             //确认到货
             if($orderDetail['status']!=2){
                 throw new FailedException(['msg'=>'订单不能确认到货']);
             }
             if(!$product_order){
                 throw new NotFoundException(['msg'=>'商城订单不存在']);
             }
             //取消订单 原来返回 原路返回 子订单走子订单 总订单走总订单 通过 pay_from 1是总订单 2是子订单 去判断 //退款走退款的
             //根据订单的支付来源 退回到原来 微信PC支付 微信APP支付
             if($product_order['pay_form']==2){
                 $order_number = $product_order['order_number'];
                 $total_fee = $product_order['total_price'];
             }else{
                 $list = (new ProductOrderRelation())->findOne([['id','eq',$product_order['relation_id']]],"order_number,total_price");
                 $order_number = $list['order_number'];
                 $total_fee =$list['total_price'];
             }
             if(TestPrice == 1){
                 $total_fee = 0.01;
                 $orderDetail['total_price'] = 0.01;//退款金额
             }
             Db::startTrans();
             $new = ['id' =>$post['id'],'status'=>3];
             if(!in_array($post['check_status'],[3])){
                 Db::rollback();
                 throw new FailedException(['msg'=>'审核状态不正确']);
             }
             $res = (new ProductOrderReturn())->dataUpdate($new);
             if(!$res){
                 Db::rollback();
                 throw new FailedException(['msg'=>'审核失败']);
             }
             Db::commit();
             return writeJson(200);
         }
     }

    /**
     * 用户发布的大单需求列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function getUserDemandList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $where['page'] = $post['page'];
        $dataList = (new UserDemand())->wechatListTotalWith("product",$where,"*","id desc",$post['page_number']);

        foreach ($dataList['data'] as &$value){
            $value['type'] = (new \app\admin\model\Product())
                ->alias("a")
                ->join("om_shop b","a.uid = b.id","left")
                ->where([['a.id','eq',$value['product_id']]])
                ->group("b.type")
                ->value("b.type");
            $value['purchase_data'] = serializeMysql($value['purchase_data'],1);
            $value['purchase_data'] =array_values($value['purchase_data']);
            $value['cover_img'] =imgUrlToAbsolute($value['cover_img']);
        }
        return writeJson(200,$dataList);
    }
}